using System;
using System.Web.UI.WebControls;
using Eneta.Portal.Forum.Controls.Base;
using Eneta.Portal.Forum.Controls.Common;
using Eneta.Portal.Forum.Core.Domain.Collections;
using Eneta.Portal.Forum.Core.Domain.Entities;
using Eneta.Portal.Forum.Core.Service.Application;

namespace Eneta.Portal.Forum.Controls
{
    public class UpdateCounts : AdminBaseControl
    {
        private SPButton btnUpdateCounts;
		
        protected override void CreateAdminChildControls()
        {
            AddBoxHeader("Update and Recalculate Forum Totals");
            AddText("This page will recalculate forum totals and update the counts for display in statistics.");
            AddText("</p>");

            btnUpdateCounts = new SPButton("Update Totals");
            btnUpdateCounts.Click += new EventHandler(btnUpdateCounts_Click);
            Controls.Add(btnUpdateCounts);
        }

        private void btnUpdateCounts_Click(object sender, EventArgs e)
        {
            int numForums = 0;
            int numTopics = 0;
            int numPosts = 0;
			
            CategoryCollection categories = RepositoryRegistry.CategoryRepository.GetAll();
            foreach (Category category in categories)
            {
                numForums += category.Forums.Count;

                foreach (Core.Domain.Entities.Forum forum in category.Forums)
                {
                    forum.TopicCount = forum.Topics.Count;
                    numTopics += forum.TopicCount;

                    forum.PostCount = 0;
                    foreach (Topic topic in forum.Topics)
                    {
                        forum.PostCount += topic.Messages.Count;
                        numPosts += forum.PostCount;
                    }

                    RepositoryRegistry.ForumRepository.Save(forum);
                }
            }

            WebPartParent.TopicCount = numTopics;
            WebPartParent.ForumCount = numForums;
            WebPartParent.PostCount = numPosts;
            WebPartParent.PersistProperties();
        }
    }
}